package cn.broadsense.thrid.api;


import cn.broadsense.common.exception.ServiceException;
import cn.broadsense.common.utils.RedisLockUtils;
import cn.broadsense.thrid.constant.DaHuaApiUrlConstant;
import cn.broadsense.thrid.utils.DaHuaHttpUtils;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * 大华接口token
 *
 * @author pengxin
 * @date 2022-10-08 11:10
 */
@Slf4j
@Component
public class DaHuaTokenRepository {

    @Value("${dh.api.xc.url:}")
    private String url;
    @Value("${dh.api.xc.username:}")
    private String userName;
    @Value("${dh.api.xc.password:}")
    private String password;

    @Value("${dh.api.c.url:}")
    protected String cUrl;
    @Value("${dh.api.c.username:}")
    protected String cUserName;
    @Value("${dh.api.c.password:}")
    protected String cPassword;
    @Value("${dh.api.c.ip:}")
    protected String cIp;


    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private RedisLockUtils redisLock;


    private static final String DH_TOKEN_LOCK_KEY = "dh:token:l";
    /**
     * C系列
     */
    private static final String DH_TOKEN_C_LOCK_KEY = "dh:c:token:l";

    /**
     * 获取token
     *
     * @return
     */
    public String getDHToken() {
       return getDhToken(false);
    }

    /**
     * 获取token 是否重置刷新
     *
     * @param isRefresh
     * @return
     */
    public synchronized String getDhToken(Boolean isRefresh) {
        //默认5秒
        try {
            //添加分布式锁
            Boolean isLock = redisLock.tryLock(DH_TOKEN_LOCK_KEY, 10, 10);
            if (!isLock) {
                log.error("获取锁失败");
                return null;
            }
            if (isRefresh) {
                redisTemplate.delete(DaHuaApiUrlConstant.REDIS_TOKEN_KEY);
            }
            String token = redisTemplate.opsForValue().get(DaHuaApiUrlConstant.REDIS_TOKEN_KEY);
            if (StrUtil.isBlank(token)) {
                JSONObject jsonObject = DaHuaHttpUtils.getToken(url, userName, password);
                token = jsonObject.getString("token");
                if (StrUtil.isBlank(token)) {
                    log.error("获取到的token为空");
                    throw new ServiceException("获取到的token为空");
                }
                redisTemplate.opsForValue().set(DaHuaApiUrlConstant.REDIS_TOKEN_KEY, token);
                redisTemplate.expire(DaHuaApiUrlConstant.REDIS_TOKEN_KEY, jsonObject.getInteger("duration") - 20, TimeUnit.SECONDS);
            }
            return token;
        } catch (Exception e) {
            log.error("获取大华token失败  失败信息：{}", e.getMessage());
        } finally {
            redisLock.unlock(DH_TOKEN_LOCK_KEY);
        }
        return null;
    }

    /**
     * 获取C系列Token
     *
     * @return
     */
    public String getDhCToken() throws ServiceException {
       return getDhCToken(false);
    }


    /**
     * 获取token 是否重置刷新
     *
     * @param isRefresh
     * @return
     */
    public synchronized String getDhCToken(boolean isRefresh){
        //默认5秒
        try {
            //添加分布式锁
            Boolean isLock = redisLock.tryLock(DH_TOKEN_C_LOCK_KEY, 10, 10);
            if (!isLock) {
                log.error("获取锁失败");
                return null;
            }
            if(isRefresh){
                redisTemplate.delete(DaHuaApiUrlConstant.REDIS_C_TOKEN_KEY);
            }
            String token = redisTemplate.opsForValue().get(DaHuaApiUrlConstant.REDIS_C_TOKEN_KEY);
            if (StrUtil.isBlank(token)) {
                String result = DaHuaHttpUtils.getCToken(cUrl, cUserName, cPassword, cIp);
                JSONObject jsonObject = JSONObject.parseObject(result);
                token = jsonObject.getString("token");
                if (StrUtil.isBlank(token)) {
                    log.error("获取到的token为空");
                    throw new ServiceException("获取到的token为空");
                }
                redisTemplate.opsForValue().set(DaHuaApiUrlConstant.REDIS_C_TOKEN_KEY, token);
                redisTemplate.expire(DaHuaApiUrlConstant.REDIS_C_TOKEN_KEY, jsonObject.getInteger("duration") - 20, TimeUnit.SECONDS);
            }
            return token;
        } catch (Exception e) {
            log.error("获取大华c系列token失败  失败信息：{}", e.getMessage());
        } finally {
            redisLock.unlock(DH_TOKEN_C_LOCK_KEY);
        }
        return null;
    }
}
